<template>
   <div class="map-selector">
    <slot name="address-input" />
    <el-button type="primary" size="small" @click="openMap">
      <el-icon><Location /></el-icon> 地图选点
    </el-button>
    <!-- 地图容器不再包在 el-dialog 里 -->
    <div v-show="showMap" class="map-mask" @click.self="closeMap">
      <div class="map-box">
        <div :key="mapKey" id="mapContainer" style="width:100%;height:400px"></div>
        <div class="map-footer">
          <el-button @click="closeMap">取消</el-button>
          <el-button type="primary" @click="handleConfirm" :disabled="selectedLngLat.length!==2">
            确认选择
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onUnmounted, nextTick } from 'vue';
import { Location } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import AMapLoader from '@amap/amap-jsapi-loader';  // 引入加载器

const emit = defineEmits(['update:modelValue']);
const showMap = ref(false);
const selectedAddress = ref([]);
const selectedLngLat = ref([]);
let mapInstance = null;
const mapKey = ref(Date.now())

// 初始化地图（使用加载器加载API）
const initMap = async () => {
  // 确保容器已渲染
  await nextTick();
   await new Promise(resolve => setTimeout(resolve, 100));

  try {
    // 加载高德地图API
    const AMap = await AMapLoader.load({
      key: '6b9cdc106cb120d6c1676e307338c949',  // 替换为你的有效密钥
      version: '1.4.15',          // 使用2.0版本
      // plugins: ['AMap.Geocoder']
      plugins:[]
    });
console.log('Geocoder是否存在:', AMap.Geocoder);
    // 初始化地图实例
    mapInstance = new AMap.Map('mapContainer', {
      zoom: 12,
      center: [116.404, 39.915],  // 初始中心点（北京）
      resizeEnable: true          // 允许地图随容器大小调整
    });

    // 点击地图选点
    mapInstance.on('click', (e) => {
      const { lnglat } = e;
      selectedLngLat.value = [lnglat.getLng(), lnglat.getLat()];

      // 逆地理编码（经纬度转地址）
      new AMap.Geocoder().getAddress(lnglat, (status, result) => {
        if (status === 'complete' && result.regeocode) {
          selectedAddress.value = result.regeocode.formattedAddress;
        } else {
           ElMessage.error('获取地址失败，请重新点击');
         }
       });
    });

  } catch (error) {
    console.error('地图初始化失败：', error);
    ElMessage.error('地图加载失败,请检查API密钥或网络');
  }
};

// 销毁地图实例
const destroyMap = () => {
  if (mapInstance) {
    mapInstance.destroy();
    mapInstance = null;
  }
  const box = document.getElementById('mapContainer');
  box?.querySelectorAll('.amap-layer, .amap-markers, .amap-controls, canvas, img').forEach(n => n.remove());
};

// 监听弹窗状态（简化逻辑）
watch(showMap, (newVal) => {
  if (!newVal) {
    destroyMap();
  }
});


// 确认选择
const handleConfirm = () => {
  if (selectedLngLat.value.length === 2) {
    // 拼成后端要的格式：经度,纬度
    const address = `${selectedLngLat.value[0]},${selectedLngLat.value[1]}`;
    emit('update:modelValue', address);   // 父级 addressInfo.address 就是这个字符串
    showMap.value = false;
    ElMessage.success('地址选择成功');
  }
};

// 组件卸载时销毁地图
onUnmounted(() => {
  destroyMap();
});
/* 1. 打开遮罩 + 初始化地图 */
const openMap = async () => {
  mapKey.value = Date.now()     // 先换新 key
  showMap.value = true
  await nextTick()
  initMap()
}

/* 2. 关闭遮罩 + 销毁地图 */
const closeMap = () => {
  showMap.value = false
  destroyMap()                  // 你原来的销毁逻辑
}

</script>

<style scoped>
#mapContainer {
  width: 100%;
  height: 400px;
  position: relative;  /* 确保地图容器定位正常 */
  z-index: 99;         /* 避免被弹窗其他元素遮挡 */
}
.map-mask{
  position: fixed;
  inset:0;
  background: var(--el-overlay-color-lighter);
  z-index: 2000;          /* 比 el-dialog 高 */
  display:flex;
  align-items:center;
  justify-content:center;
}
.map-box{
  background:#fff;
  border-radius:4px;
  box-shadow:0 2px 12px 0 rgba(0,0,0,.1);
  width:700px;
  max-width:90vw;
}
.map-footer{
  padding:10px 16px;
  text-align:right;
}
</style>
